<template>
  <div>
    <el-table :data="products" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="name" label="商品名称"></el-table-column>
      <el-table-column prop="categoryName" label="分类"></el-table-column>
      <el-table-column prop="price" label="价格" width="120"></el-table-column>
      <el-table-column prop="stock" label="库存" width="100"></el-table-column>
      <el-table-column label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? "上架" : "下架" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button
            size="small"
            :type="row.status === 1 ? 'warning' : 'success'"
            @click="toggleStatus(row)"
          >
            {{ row.status === 1 ? "下架" : "上架" }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      layout="prev, pager, next"
      @current-change="fetchProducts"
      style="margin-top: 20px"
    ></el-pagination>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";

const products = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 模拟获取商品数据
const fetchProducts = async () => {
  // 这里应该是API调用，我们模拟数据
  products.value = [
    {
      id: 1,
      name: "高级狗粮",
      category: 1,
      categoryName: "狗粮",
      price: 120,
      stock: 50,
      status: 1,
    },
    {
      id: 2,
      name: "猫砂",
      category: 2,
      categoryName: "猫用品",
      price: 80,
      stock: 100,
      status: 1,
    },
    {
      id: 3,
      name: "宠物玩具",
      category: 3,
      categoryName: "玩具",
      price: 45,
      stock: 30,
      status: 0,
    },
    {
      id: 4,
      name: "宠物维生素",
      category: 4,
      categoryName: "保健品",
      price: 150,
      stock: 20,
      status: 1,
    },
  ];
  total.value = 4;
};

const toggleStatus = (product) => {
  product.status = product.status === 1 ? 0 : 1;
  ElMessage.success(`商品已${product.status === 1 ? "上架" : "下架"}`);
};

onMounted(() => {
  fetchProducts();
});
</script>
